package chat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class Server {
    private static final int BUFFER_SIZE = 1024;

    static ArrayList<Socket> list = new ArrayList<>();

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(9960)) {
            while (true) {
                Socket accept = serverSocket.accept();

                //***新线程***/
                list.add(accept);

                MessageHandler messageHandler = new MessageHandler(accept);
                messageHandler.start();

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

/**
 * 主要负责获取当前socket中的数据，并分发给当前聊天室的所有客户端。
 */
class MessageHandler extends Thread {
    private Socket socket;
    private String ip;

    @Override
    public void run() {
        try {
            ip = socket.getInetAddress().getHostAddress();
            // 发送上线通知
            sendToOthers(ip + "上线了");
            // 接收该客户端发送的消息
            InputStream inputStream = socket.getInputStream();
            Scanner scanner = new Scanner(inputStream);

//            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
//            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//            String str;
            while ((scanner.hasNextLine())) {
                // 转发
                sendToOthers(ip + ":" + scanner.nextLine());
                System.out.println(ip + ":" + scanner.nextLine());
            }

            // 下线通知
            sendToOthers(ip + "下线了");

        } catch (IOException e) {
            // 掉线通知
            try {
                sendToOthers(ip + "掉线了");

            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            // 从列表中删除该socket
            Server.list.remove(socket);
        }
    }

    public MessageHandler(Socket socket) {
        this.socket = socket;
    }

    void sendToOthers(String msg) throws IOException {
        for (Socket s : Server.list) {
            OutputStream outputStream = s.getOutputStream();
            // 使用PrintStream，实现按行打印
            PrintStream printStream = new PrintStream(outputStream);
            printStream.println(msg);
        }
    }
}
